package com.htu.hdfs;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class ListFiles {
	
	public static Configuration getConf() {
		Configuration conf = new Configuration();
		return conf;
	}

	public static FileSystem initHdfs(String hdfsPath, Configuration conf)
			throws IOException, URISyntaxException {
		FileSystem fs = FileSystem.get(new URI(hdfsPath), conf);
		return fs;
	}

	public static void doListFiles(FileSystem fs, String dir, String param) throws IllegalArgumentException, IOException {
		FileStatus[] files = fs.listStatus(new Path(dir));
		if(param.equals("-R")){
			iteratorListFile(fs,new Path(dir));
		}else{
			for (FileStatus file : files) {
				String fileType = file.isDirectory() ? "d" : "-";
				System.out.println(
						fileType +
						file.getPermission()
						+ " " + file.getOwner()
						+ " " + file.getGroup()
						+ " " + file.getPath()
				);
			}
		}
	}
	
	public static void iteratorListFile(FileSystem hdfs, Path path)throws FileNotFoundException, IOException {
		
		FileStatus[] files = hdfs.listStatus(path);
		for (FileStatus file : files) {
			String fileType = file.isDirectory() ? "d" : "-";
			if (file.isDirectory()) {
					System.out.println(fileType + file.getPermission() + " " + file.getOwner()
							 + " " + file.getGroup() + " " + file.getPath());
							iteratorListFile(hdfs, file.getPath());
			} else if (file.isFile()) {
				System.out.println(fileType + file.getPermission() + " " + file.getOwner()
						+ " " + file.getGroup() + " " + file.getPath());
			}
		}
	}

	public static void main(String[] args) throws IOException, URISyntaxException {
		
		//获取配置信息
		Configuration conf = getConf();

		//初始化
		FileSystem hdfs = initHdfs(args[0],conf);
		
		//执行命令
		//String from_HDFS = "/hdfstest";
		doListFiles(hdfs,args[1],args[2]);

	}

}
